﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SeDuce.BLL;
using SeDuce.DAL;
using System.IO;
using System.Data;
using SeDuce.Model;
using System.Text;
using System.Data.SqlClient;

public partial class Management_News_List : PagerBase
{
    List<int> newsIDs = new List<int>();

    Lazy_Yu<NewsBLL> lazyNewsBLL = new Lazy_Yu<NewsBLL>(() => new NewsBLL());
    public NewsBLL LazyNewsBLL
    {
        get { return this.lazyNewsBLL.Value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.BindGridView();
        
    }

    protected void lbtnADD_Click(object sender, EventArgs e)
    {
        Response.Redirect("Add.aspx");
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridViewRow row = ((LinkButton)e.CommandSource).Parent.Parent as GridViewRow;
        string strID = ((Label)this.GridView1.Rows[row.RowIndex].Cells[1].FindControl("lblID")).Text.Trim();
        if (e.CommandName == "MOD")
        {
            Response.Redirect("Modify.aspx?NewsID=" + strID);
        }
        else if (e.CommandName == "DEL")
        {
            string oldLogo = ((HiddenField)this.GridView1.Rows[row.RowIndex].Cells[2].FindControl("hidLogo")).Value.Trim();
            this.LazyNewsBLL.DeleteNews(strID.ToInt());
            if (File.Exists(Server.MapPath(oldLogo)))
            {
                File.Delete(Server.MapPath(oldLogo));
            }
            this.BindPage(this.rptPageFliper.UniqueID, 1);
        }
    }

    protected void ddlSeq_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlSeq = ((DropDownList)sender);
        GridViewRow row = (GridViewRow)ddlSeq.Parent.Parent;
        string seq = ddlSeq.SelectedValue;
        int intID = ((Label)row.Cells[1].FindControl("lblID")).Text.ToInt();
        DataTable dtNews = this.LazyNewsBLL.GetNewsByID(intID);
        News news = dtNews.ToList<News>().SingleOrDefault();
        news.Seq = seq.ToInt();
        if (dtNews.Rows.Count > 0)
        {
            bool result = this.LazyNewsBLL.UpdateNews(news);
            if (result)
            {
                switch (seq)
                {
                    case "2"://置顶
                        ddlSeq.BackColor = System.Drawing.Color.OrangeRed;
                        break;
                    case "0"://置底
                        ddlSeq.BackColor = System.Drawing.Color.DarkGreen;
                        break;
                    default:
                        ddlSeq.BackColor = System.Drawing.Color.DarkGray;
                        break;
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key6", "javascript:" + string.Format("alert('{0}');", "保存时发生错误!请重试..."), true);
            }
        }
    }

    protected void chkIsInGallery_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkIsInGallery = ((CheckBox)sender);
        GridViewRow row = (GridViewRow)chkIsInGallery.Parent.Parent;
        int intID = ((Label)row.Cells[1].FindControl("lblID")).Text.ToInt();
        DataTable dtNews = this.LazyNewsBLL.GetNewsByID(intID);
        News news = dtNews.ToList<News>().SingleOrDefault();
        news.IsInGallery = chkIsInGallery.Checked;
        if (dtNews.Rows.Count > 0)
        {
            bool result = this.LazyNewsBLL.UpdateNews(news);
            if (result)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key7", "javascript:" + string.Format("Seduce.Alert.show('{0}','{1}');", chkIsInGallery.ClientID, "操作成功"), true);
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key7", "javascript:" + string.Format("alert('{0}');", "保存时发生错误!请重试..."), true);
            }
        }
    }

    //protected void chkIsHeadline_CheckedChanged(object sender, EventArgs e)
    //{
    //    CheckBox chkIsHeadline = ((CheckBox)sender);
    //    GridViewRow row = (GridViewRow)chkIsHeadline.Parent.Parent;
    //    int intID = ((Label)row.Cells[1].FindControl("lblID")).Text.ToInt();
    //    DataTable dtNews = this.LazyNewsBLL.GetNewsByID(intID);
    //    News news = dtNews.ToList<News>().SingleOrDefault();
    //    news.IsHeadline = chkIsHeadline.Checked;
    //    if (dtNews.Rows.Count > 0)
    //    {
    //        bool result = this.LazyNewsBLL.UpdateNews(news);
    //        if (result)
    //        {
    //            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key7", "javascript:" + string.Format("Seduce.Alert.show('{0}','{1}');", chkIsHeadline.ClientID, "操作成功"), true);
    //        }
    //        else
    //        {
    //            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key8", "javascript:" + string.Format("alert('{0}');", "保存时发生错误!请重试..."), true);
    //        }
    //    }
    //}

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlSeq = (DropDownList)e.Row.FindControl("ddlSeq");
            DataRowView row = (DataRowView)e.Row.DataItem;
            string seq = row["Seq"] != DBNull.Value ? row["Seq"].ToString() : string.Empty;
            this.DropDownListFixByValue(ddlSeq, seq);
            switch (seq)
            {
                case "2"://置顶
                    ddlSeq.BackColor = System.Drawing.Color.OrangeRed;
                    break;
                case "0"://置底
                    ddlSeq.BackColor = System.Drawing.Color.DarkGreen;
                    break;
                default:
                    ddlSeq.BackColor = System.Drawing.Color.DarkGray;
                    break;
            }
        }
    }

    protected void lbtnSearch_Click(object sender, EventArgs e)
    {
        this.AddAttributes("TbNews.Title|like", this.txtSearchName.Text.Trim());
        this.BindGridView();
        this.BindPage(this.rptPageFliper.UniqueID, 1);
    }

    private void BindGridView()
    {
        StringBuilder where = new StringBuilder();
        List<SqlParameter> sp = new List<SqlParameter>();
        Dictionary<string, string> attrs = this.GetAllAttributes();
        foreach (KeyValuePair<string, string> attr in attrs)
        {
            if (!attr.Key.StartsWith("Sort_") && !string.IsNullOrEmpty(attr.Value))
            {
                string key = attr.Key.Split('|')[0];
                string option = attr.Key.Split('|')[1];
                string format = string.Empty;
                switch (option)
                {
                    case "eq":
                        format = " AND {0}=@{1}";
                        sp.Add(new SqlParameter("@" + key.Split('.')[1], attr.Value));
                        break;
                    case "like":
                        format = " AND {0} like @{1}";
                        sp.Add(new SqlParameter("@" + key.Split('.')[1], "%" + attr.Value + "%"));
                        break;
                    default:
                        break;
                }
                where.Append(string.Format(format, key, key.Split('.')[1]));
            }
        }


        this.RegistrPager(this.GridView1, this.rptPageFliper, 7, this.FillPageMoudleWithParams(20, SeDuce.DAL.NewsDAL.sqlGetNews + where.ToString(), sp.ToArray(), new List<SortField>() { 
            new SortField() { FieldName = "ID", DESC = false }
        }));

    }

    protected void lbtnBack_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> attrs = this.GetAllAttributes();
        List<string> keys = new List<string>();
        foreach (KeyValuePair<string, string> attr in attrs)
        {
            if (!attr.Key.StartsWith("Sort_") && !string.IsNullOrEmpty(attr.Value))
            {
                keys.Add(attr.Key);
            }
        }
        keys.ForEach(k => this.RemoveAttributes(k));

        this.BindGridView();
        this.BindPage(this.rptPageFliper.UniqueID, 1);
    }

    protected void ddlIsHeadline_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlIsHeadline = ((DropDownList)sender);
        GridViewRow row = (GridViewRow)ddlIsHeadline.Parent.Parent;
        string status = ddlIsHeadline.SelectedValue;
        int intNewsID = ((Label)row.Cells[1].FindControl("lblID")).Text.ToInt();
        DataTable dtNews = this.LazyNewsBLL.GetNewsByID(intNewsID);
        if (dtNews.Rows.Count > 0)
        {
            bool result = this.LazyNewsBLL.UpdateNews(new News()
            {
                ID = dtNews.Rows[0]["ID"].ToString().ToInt(),
                Title = dtNews.Rows[0]["Title"].ToString(),
                ContentText = dtNews.Rows[0]["ContentText"].ToString(),
                UpdateDate = Convert.ToDateTime(dtNews.Rows[0]["UpdateDate"]),
                Pic = dtNews.Rows[0]["Pic"].ToString(),
                TypeID = dtNews.Rows[0]["TypeID"].ToString().ToInt(),
                IsInGallery = Convert.ToBoolean(dtNews.Rows[0]["IsInGallery"]),
                IsHeadline = status.ToInt()
            });
            if (result)
            {
                switch (status)
                {
                    case "1"://图片
                        ddlIsHeadline.BackColor = System.Drawing.Color.Orange;
                        break;
                    case "2"://文字
                        ddlIsHeadline.BackColor = System.Drawing.Color.LightBlue;
                        break;
                    default:
                        ddlIsHeadline.BackColor = System.Drawing.Color.DarkGray;
                        break;
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key6", "javascript:" + string.Format("alert('{0}');", "保存时发生错误!请重试..."), true);
            }
        }
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        int num = 0;
        if (int.TryParse(this.txtPageNum.Text.Trim(), out num))
        {
            if (num <= this.TotalPage(this.rptPageFliper.UniqueID) && num > 0)
            {
                this.BindGridView();
                this.BindPage(this.rptPageFliper.UniqueID, num);
            }
        }
    }

    protected void lbtnDelete_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow item in this.GridView1.Rows)
        {
            CheckBox chk = (CheckBox)item.Cells[7].FindControl("chkCheck");
            if (chk.Checked)
            {
                int intNewsID = ((Label)item.Cells[1].FindControl("lblID")).Text.ToInt();
                newsIDs.Add(intNewsID);
            }
        }
        if (newsIDs.Count > 0)
        {
            if (this.LazyNewsBLL.DeleteNews(newsIDs))
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key7", "javascript:alert('删除成功!');", true);
                this.BindPage(this.rptPageFliper.UniqueID, 1);
            }
        }
        else {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key8", "javascript:alert('请先选择新闻');", true);
        }
        
    }
}